<template>
  <div class="exam-detail">
    <g-question v-if="question.id" v-model="answer" v-bind="question" />

    <fixed-bottom v-if="total">
      <span class="question-index"><van-icon name="orders-o" />{{ index }} / {{ total }}</span>
      <van-button v-if="index !== total" type="primary" @click="next()">确定, 下一题</van-button>
      <van-button v-else type="primary" @click="next(true)">提交</van-button>
    </fixed-bottom>
  </div>
</template>

<script>
import FixedBottom from '@/components/FixedBottom'
import { Button, Icon } from 'vant'
import { getQuestions, saveExam } from '../api'
import GQuestion from '@/components/Question.vue'
import { mapGetters } from 'vuex'
import Taro from '@tarojs/taro'

export default {
  components: {
    FixedBottom,
    GQuestion,
    [Button.name]: Button,
    [Icon.name]: Icon
  },
  data() {
    return {
      questions: [],
      index: 1,
      answer: '',
      form: {
        exam: {},
        detailList: []
      }
    }
  },
  computed: {
    ...mapGetters(['exam']),
    total() {
      return this.questions.length
    },
    question() {
      return this.questions[this.index - 1] || {}
    }
  },
  onLoad(options) {
    this.setExam()
    this.getDetail(options.id)
  },
  methods: {
    setExam() {
      const { id: titleId, name: titleName, result, abbr: type } = this.exam
      this.form.exam = {
        titleId,
        titleName,
        type,
        result,
        score: 0
      }
    },
    next(save = false) {
      if (!this.answer) {
        this.showMsg('请选择答案')
        return
      }
      this.form.detailList.push({
        questionId: this.question.id,
        answer: this.answer
      })
      this.form.exam.score += this.question[this.answer]
      if (save) {
        this.save()
      } else {
        this.answer = ''
        this.index++
      }
    },
    async save() {
      if (this.exam.type) {
        const results = JSON.parse(this.exam.result)
        const result = results.find(item => this.inRange(item, this.form.exam.score))
        this.form.exam.result = result.result
      }
      await saveExam(this.form)
      this.showMsg('已保存', 'success')
      this.$store.commit('setEvaluation', this.form.exam)
      Taro.redirectTo({
        url: '/pages/evaluation/result/index'
      })
    },
    async getDetail(id) {
      const { data: questions, done } = await getQuestions(id)
      if (done) {
        Taro.showModal({
          title: '温馨提示',
          content: '您已评测过该问卷, 请三个月后再评测',
          showCancel: false,
          success: () => {
            this.back()
          }
        })
        return
      }
      Taro.showModal({
        title: this.exam.name,
        content: this.exam.summarize,
        confirmText: '开始测评',
        success: ({ confirm }) => {
          if (confirm) {
            this.questions = questions.map(this.formatQuestion)
          } else {
            this.back()
          }
        }
      })
    },
    formatQuestion(question, index) {
      const { title, id } = question
      const scoreMap = {}
      const options = ['a', 'b', 'c', 'd', 'e', 'f'].reduce((pre, cur) => {
        if (question[cur]) {
          scoreMap[cur] = question['v' + cur]
          pre.push({
            label: question[cur],
            value: cur
          })
        }
        return pre
      }, [])
      return {
        title: (index + 1) + '. ' + title,
        id,
        ...scoreMap,
        options
      }
    },
    inRange({ start, end }, score) {
      return score >= start && score <= end
    }
  }
}
</script>

<style lang="less">
@import './index.less';
</style>
